package org.quartz.watch.dc.impl;

import java.util.List;
import java.util.logging.Level;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.watch.QWContext;
import org.quartz.watch.QWLogger;
import org.quartz.watch.dc.QWSchedulerDialogController;

public class QWSchedulerDC<C extends QWAbstractDC.Record<?>> extends QWAbstractDC<C> implements QWSchedulerDialogController<C> {
	private Scheduler scheduler;
	
	public QWSchedulerDC() {
		try {
			retreiveScheduler();
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
	}
	
	@Override
	public int getRecordCount() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<C> getRecords() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean navigationActionPerformed() {
		return true;
	}
	
	public String stopSchedulerActionPerformed() {
		try {
			getScheduler().shutdown();
			Thread.sleep(1000);
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return "no_op";
	}
	
	public String startSchedulerActionPerformed() {
		QWContext.getInstance().getSchedulerDialogController();
		try {
			if(isSchedulerShutdown()) {
				retreiveScheduler();
			}
			getScheduler().start();
			Thread.sleep(1000);
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return "no_op";
	}
	
	public String pauseSchedulerActionPerformed() {
		try {
			getScheduler().standby();
			Thread.sleep(1000);
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return "no_op";
	}
	
	public String resumeSchedulerActionPerformed() {
		try {
			getScheduler().resumeAll();
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return "no_op";
	}
	
	public String refreshSummaryActionPerformed() {
		try {
			Thread.sleep(1000);
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return "no_op";
	}
	
	public boolean isSchedulerStarted() {
		try {
			return getScheduler().getMetaData().isStarted();
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return false;
	}
	
	public boolean isSchedulerPaused() {
		try {
			return getScheduler().isInStandbyMode();
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return false;
	}
	
	public boolean isSchedulerShutdown() {
		try {
			return getScheduler().isShutdown();
		}
		catch(Exception e) {
			QWLogger.getLogger().log(Level.SEVERE, "", e);
		}
		return false;
	}
	
	private void retreiveScheduler() throws SchedulerException {
		scheduler = StdSchedulerFactory.getDefaultScheduler();
	}

	public Scheduler getScheduler() throws SchedulerException {
		return scheduler;
	}
}
